package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;


import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.redis.datatype.RedisHashUtils;
import com.mjk.common.core.redis.datatype.RedisUtils;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.web.getway.constns.GetWayError;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.prototal.http.BaseController;
import jakarta.servlet.http.HttpSession;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;

/**
 * 单点登录
 * @author mjk
 *
 */
@BeeGetWayInterceptor(value=3)
@ConditionalOnProperty(name="bee.single.login",havingValue="true")
public class GetWaySinglePointLoginInterceptor implements GetWayInterceptor {
	
public static final String COOKIE = "cookie";//request中的cookie标签名称
	
	public static final String USER_PARAMS = "userName";//参数中用户名字段
	
	public static final String USER_SESSION = "loginUser:";//用户session的标头
	/**
	 * 豁免账号
	 */
	protected static final String[] PASS_ACCOUNT = new String[]{"9999"};
	
	private final String[] PASSSQLID = new String[]{"BRXZCX","RYBQCX","RYFSCX","LSTD","FYDWZDCX","ZZBZCXCX","GYBRCX"};
	
	private final String[] PASSDICTNAME = new String[]{"sysdate","system_param","sys_module","sys_sysfunctions","sys_user_group"};
	/**
	 * 不同容器中的session名称
	 */
	private final String[] CONTAIN_SESSION_NAME = new String[]{"SESSION","JSESSIONID"};
	
	@SuppressWarnings("rawtypes")
    private final RedisTemplate redisTemplate;

    public GetWaySinglePointLoginInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @SuppressWarnings("unchecked")
	@Override
	public BeeResponse interceptor(GetWayInterceptorReq request,
								   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
		Map<String,Object> paraseMap = request.getParams();
		//对于放行URL 的处理
		String method = MapUtils.getString(paraseMap, GetwayConsts.METHOD);
		if(request.getRequest().getRequestURI().contains("/ld/common/v1/loginservice")
				||request.getRequest().getRequestURI().contains("/ld/common/dict/loginservice")){			
			if(ObjectUtils.isNotEmpty(method)&&method.equals("initDict")){
				return next.proceed(request);
			}
			if(ObjectUtils.isNotEmpty(method)&&method.equals("login")){
				BeeResponse response =next.proceed(request);
				if(response.getCode().equals(1)){
					request.getRequest().getSession().setAttribute(BaseController.SYS_USER_SESSION_NAME, response.getData());
					//记录到springsession中
					HttpSession session = request.getRequest().getSession();
					String sessionId = session.getId();	        		
					boolean isPassAccount = false;
					String userName = MapUtils.getString(paraseMap, GetwayConsts.USERNAME);
			        //对9999账号的豁免 
					for(String account : PASS_ACCOUNT){
						if(userName.equals(account)){
							if(redisTemplate.opsForHash().size(USER_SESSION + userName)>100){
				        		redisTemplate.delete(USER_SESSION + userName);
				        	}
							if(!RedisHashUtils.exists(redisTemplate,USER_SESSION + userName, sessionId)){
								RedisHashUtils.set(redisTemplate, USER_SESSION + userName,
										sessionId, sessionId);
							}
				        	isPassAccount = true;
						}
					}	
			        if(!isPassAccount){
			        	redisTemplate.opsForValue().set(sessionId,USER_SESSION + userName );
			        	String userSession = (String) RedisUtils.get(redisTemplate, USER_SESSION + userName);
			        	if(!ObjectUtils.isEmpty(userSession)){			
							redisTemplate.delete(userSession);
						}
			        	redisTemplate.opsForValue().set(USER_SESSION + userName , sessionId);
			        }			       
				}
				return response;
			}
		}
		String sqlId = MapUtils.getString(paraseMap, "sqlId");
		if(request.getRequest().getRequestURI().contains("/ld/common/dict/sql")){			
			if(ObjectUtils.isNotEmpty(sqlId)){
				for(String id : PASSSQLID){
					if(sqlId.contains(id)){
						return next.proceed(request);
					}
				}				
			}
		}//过滤DICT
		String dictName = MapUtils.getString(paraseMap, "dict");
		if(request.getRequest().getRequestURI().contains("/ld/common/dict/dict")){			
			if(ObjectUtils.isNotEmpty(dictName)){
				for(String id : PASSDICTNAME){
					if(dictName.contains(id)){
						return next.proceed(request);
					}
				}				
			}
		}
		if(request.getRequest().getRequestURI().contains("/ld/common/dict/ybmain")){			
			if("getDict".equals(method)){				
				return next.proceed(request);				
			}
		}
		
		// 验证当前请求的session是否是已登录的session
		// 判断逻辑为 登录成功之后 sessionId : userName 存入redis
		// 这里判断 带上来的sessionID 如果存在，就说明 该用户已经登入
		String sessionId = request.getHeadParams().get(COOKIE);
		for(String sessionName : CONTAIN_SESSION_NAME){
			if(sessionId!=null&&sessionId.contains(sessionName+"=")){
				sessionId = sessionId.substring(sessionId.indexOf(sessionName+"=")+(sessionName+"=").length());
				if(sessionId.contains(";"))
					sessionId = sessionId.substring(0, sessionId.indexOf(";"));
			}
		}					
		if(ObjectUtils.isNotEmpty(sessionId)){
			//对于9999账号，判断 userName:9999中是否存在
			for(String account : PASS_ACCOUNT){					
				if(RedisHashUtils.exists(redisTemplate,USER_SESSION+account,sessionId)){
					return next.proceed(request);
				}
			}

			if(ObjectUtils.isNotEmpty(RedisUtils.get(redisTemplate,sessionId))){
				return next.proceed(request);
			}
		}else{		
			BizLogger.info("sessionId:"+sessionId);
		}
		return GetWayError.SESSION_TIMEOUT.tranceError("");
	}

}
